# -*- coding: utf-8 -*-
'''
Created on 2012-4-19

@author: deadblue
'''
from cn._2dland import model
from cn._2dland.handler import exception
from google.appengine.api import users
from google.appengine.ext import webapp
import page
import simplejson as json

class IndexHandler(webapp.RequestHandler):
    def get(self):
        if users.is_current_user_admin():
            url = '/account'
        else:
            url = users.create_login_url('/account')
        self.redirect(url)

class AccountHandler(webapp.RequestHandler):
    def get(self):
        # 显示账户列表
        vars = {'title': u'115帐号管理', 'accounts': model.account.all()}
        pg = page.Page('account.html')
        pg.write(self.response.out, vars)

class AccountCreateHandler(webapp.RequestHandler):
    def post(self):
        result = {'ok': 0}

        try:
            un = self.request.get('un')
            pw = self.request.get('pw')
            st = int(self.request.get('st'))

            acnt = model.account.get_by_key_name(un)
            if acnt is not None:
                raise exception.AccountAlreadyExistsException()
            
            acnt = model.account(key_name=un, username=un, password=pw, status=st, action=0)
            acnt.put()

            result['ok'] = 1
            result['id'] = acnt.key()
        except Exception:
            result['ok'] = 0
        
        self.response.out.write(json.dumps(result))


class AccountUpdateHandler(webapp.RequestHandler):
    def post(self):
        result = {'ok': 0}

        try:
            un = self.request.get('un')
            if un is None:
                raise exception.InvalidRequestException()

            acnt = model.account.get_by_key_name(un)
            if acnt is None:
                raise exception.AccountNotFoundException()

            # 修改密码
            pw = self.request.get('pw')
            if pw is not None:
                acnt.password = pw

            # 更新状态
            st = self.request.get('st')
            if st is not None:
                acnt.status = int(st)

            acnt.put()

            result['ok'] = 1
            result['id'] = acnt.key()
        except Exception:
            result['ok'] = 0
        
        self.response.out.write(json.dumps(result))

class AccountResetHandler(webapp.RequestHandler):
    def get(self):
        self.post()
    
    def post(self):
        acnts = model.account.all()
        acnts.filter('status != ', 0)
        for acnt in acnts:
            acnt.status = 0
            acnt.put()
        self.response.out.write('ok!')


